package com.haibei.view;

import java.util.ArrayList;

import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import com.haibei.R;

public class Tab  {

	private View rootView;
	private LinearLayout tabContainer;
	private Activity activity;

	private ArrayList<View> indicators;
	private OnTabClickListener onTabClickListener;

	private ArrayList<SingleTabInidcatorView> tabs;

	public Tab(Activity activity) {
		this.indicators = new ArrayList<View>();
		this.rootView = View.inflate(activity, R.layout.tab_buttons_view, null);
		this.tabContainer = (LinearLayout) this.rootView.findViewById(R.id.linearLayoutTabs);
		this.tabs = new ArrayList<SingleTabInidcatorView>();
	}

	public void check(int index){
		SingleTabInidcatorView tabIndicator = this.tabs.get(index);
		checkTab(tabIndicator);
		if (null != onTabClickListener) {
			onTabClickListener.onClick(tabIndicator);
		}
	}
	
	public void addTab(final SingleTabInidcatorView tabIndicator) {
		this.tabs.add(tabIndicator);
		
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT, 1.0f);
		View view = tabIndicator.getView();
		indicators.add(view);
		
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				checkTab(tabIndicator);
				if (null != onTabClickListener) {
					onTabClickListener.onClick(tabIndicator);
				}
			}
		});
		
		this.tabContainer.addView(view, lp);
	}

	public void clearTabs(){
		this.tabContainer.removeAllViews();
	}
	/**
	 * 选中某个tab
	 * 
	 * @param singInidcatorView
	 */
	public void checkTab(SingleTabInidcatorView singInidcatorView) {
		
		for(int i=0,isize=tabs.size();i<isize;i++){
			SingleTabInidcatorView indicator=tabs.get(i);
			if (indicator.equals(singInidcatorView)) {
				indicator.check();
			} else {
				indicator.uncheck();
			}
		}

	}

	public View getView() {
		return rootView;
	}

	public OnTabClickListener getOnTabClickListener() {
		return onTabClickListener;
	}

	public void setOnTabClickListener(OnTabClickListener onTabClickListener) {
		this.onTabClickListener = onTabClickListener;
	}

	public static interface OnTabClickListener {
		public void onClick(SingleTabInidcatorView indicator);
	}
}
